/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2024-03-19     weihui       the first version
 */

//#include <rtthread.h>
//#include <rtdevice.h>
#include <Bsp/bsp_i2c1.h>
#include "Bsp/bsp_converter.h"

#define I2C1_BUS_NAME          "i2c1"  /* 传感器连接的I2C总线设备名称 */

static struct rt_i2c_bus_device *i2c_bus = RT_NULL;     /* I2C总线设备句柄 */

/* 写传感器寄存器 */
static rt_err_t write_reg(struct rt_i2c_bus_device *bus,rt_uint8_t addr, rt_uint8_t reg, rt_uint8_t *data)
{
    rt_uint8_t buf[3];
    struct rt_i2c_msg msgs;
    rt_uint32_t buf_size = 1;

    buf[0] = reg; //cmd
    if (data != RT_NULL)
    {
        buf[1] = data[0];
        buf[2] = data[1];
        buf_size = 3;
    }

    msgs.addr = addr;
    msgs.flags = RT_I2C_WR;
    msgs.buf = buf;
    msgs.len = buf_size;

    /* 调用I2C设备接口传输数据 */
    if (rt_i2c_transfer(bus, &msgs, 1) == 1)
    {
        return RT_EOK;
    }
    else
    {
        return -RT_ERROR;
    }
}

/* 读传感器寄存器数据 */
static rt_err_t read_regs(struct rt_i2c_bus_device *bus, rt_uint8_t addr,rt_uint8_t len, rt_uint8_t *buf)
{
    struct rt_i2c_msg msgs;

    msgs.addr = addr;
    msgs.flags = RT_I2C_RD;
    msgs.buf = buf;
    msgs.len = len;

    /* 调用I2C设备接口传输数据 */
    if (rt_i2c_transfer(bus, &msgs, 1) == 1)
    {
        return RT_EOK;
    }
    else
    {
        return -RT_ERROR;
    }
}

uint16_t read_sensor_value(uint8_t addr,uint8_t reg)
{
    uint16_t value =0;
    rt_uint8_t temp[2];
    rt_enter_critical();
    write_reg(i2c_bus, addr, reg, RT_NULL);      /* 发送命令 */
    rt_exit_critical();

    rt_enter_critical();
    read_regs(i2c_bus, addr, 2, temp);                /* 获取传感器数据 */
    rt_exit_critical();
    /* 数据转换 */
    value = bsp_cnv_arr_to_uint16(&temp[0], true);
    return value;
}

void bsp_i2c1_init(void)
{
    rt_pin_mode(I2C_DIR_PIN, PIN_MODE_OUTPUT);
    rt_pin_write(I2C_DIR_PIN,0);
    /* 查找I2C总线设备，获取I2C总线设备句柄 */
    i2c_bus = (struct rt_i2c_bus_device *)rt_device_find(I2C1_BUS_NAME);

    if (i2c_bus == RT_NULL)
    {
        rt_kprintf("can't find %s device!\n", I2C1_BUS_NAME);
    }
}


